<template>
    <canvas ref="canvasRef" class="index_bg" />
  </template>
  
  <script setup>
  import { onMounted, onBeforeUnmount, ref } from 'vue'
  
  const canvasRef = ref(null)
  
  let animationFrameId = null
  let particles = []
  let ctx = null
  let mouse = { x: null, y: null, max: 20000 }
  
  const resize = () => {
    const canvas = canvasRef.value
    if (!canvas) return
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
  }
  
  const initParticles = (count = 200) => {
    const canvas = canvasRef.value
    const width = canvas.width
    const height = canvas.height
    const a = Math.random
    particles = []
    for (let i = 0; i < count; i++) {
      particles.push({
        x: a() * width,
        y: a() * height,
        xa: 2 * a() - 1,
        ya: 2 * a() - 1,
        max: 6000,
      })
    }
  }
  
  const animate = () => {
    const canvas = canvasRef.value
    if (!canvas || !ctx) return
  
    const width = canvas.width
    const height = canvas.height
    ctx.clearRect(0, 0, width, height)
  
    const allParticles = [mouse, ...particles]
  
    particles.forEach((p, i) => {
      p.x += p.xa
      p.y += p.ya
      p.xa *= p.x > width || p.x < 0 ? -1 : 1
      p.ya *= p.y > height || p.y < 0 ? -1 : 1
      ctx.fillRect(p.x - 0.5, p.y - 0.5, 1.5, 1.5)
  
      for (let j = i + 1; j < allParticles.length; j++) {
        const p2 = allParticles[j]
        if (p2.x === null || p2.y === null) continue
        const dx = p.x - p2.x
        const dy = p.y - p2.y
        const dist = dx * dx + dy * dy
        if (dist < p2.max) {
          const ratio = (p2.max - dist) / p2.max
          ctx.beginPath()
          ctx.lineWidth = ratio / 2
          ctx.strokeStyle = `rgba(255,255,255,${ratio + 0.2})`
          ctx.moveTo(p.x, p.y)
          ctx.lineTo(p2.x, p2.y)
          ctx.stroke()
        }
      }
    })
  
    animationFrameId = requestAnimationFrame(animate)
  }
  
  onMounted(() => {
    const canvas = canvasRef.value
    if (!canvas) return
    ctx = canvas.getContext('2d')
    resize()
    initParticles()
  
    window.addEventListener('resize', resize)
    window.addEventListener('mousemove', (e) => {
      mouse.x = e.clientX
      mouse.y = e.clientY
    })
    window.addEventListener('mouseout', () => {
      mouse.x = null
      mouse.y = null
    })
  
    animate()
  })
  
  onBeforeUnmount(() => {
    cancelAnimationFrame(animationFrameId)
    window.removeEventListener('resize', resize)
  })
  </script>
  
  <style scoped>
  </style>
  